package com.appli.RebeccaBlackClic;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.*;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.scoreloop.client.android.core.controller.RequestController;
import com.scoreloop.client.android.core.controller.RequestControllerObserver;
import com.scoreloop.client.android.core.controller.ScoresController;
import com.scoreloop.client.android.core.model.Score;
import com.scoreloop.client.android.core.model.SearchList;
import com.scoreloop.client.android.ui.EntryScreenActivity;
import com.scoreloop.client.android.ui.OnScoreSubmitObserver;
import com.scoreloop.client.android.ui.ScoreloopManagerSingleton;
import com.scoreloop.client.android.ui.ShowResultOverlayActivity;

/**
 * @author AndroidMythicTeam
 * @version 26-04-2011 - Ajout du chronometre et gestion des preferences 
 * @version 26-04-2011 - Ajout du ScoreLoopManagement
 */
public class RebeccaBlackClic extends Activity implements OnClickListener, OnScoreSubmitObserver, RequestControllerObserver  {

	private static final String MY_AD_UNIT_ID = "a14dce4b0e11096";
	/* Variables */
	private Button boutonRejouer;
	private Button boutonScoreloopProfile;
	private Button boutonSubmitScore;
	private Chronometer chronometre;
	private ProgressDialog progressDialog;
	private ImageButton imageBoutonBieber;
	private TextView texteIntro;
	private TextView texteScore;
	private Boolean init = false;
	private Boolean finish = false;
	private Integer i = 0;
	GoogleAnalyticsTracker tracker;
	
	// UPDATE FAN
	private ImageView imageFan;
	private TextView meilleurJoueur;
	ScoresController scoresController;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		tracker = GoogleAnalyticsTracker.getInstance();

		tracker.start("UA-23011636-6",20, this);
		tracker.trackPageView("/HomeScreen");

		// Create the adView
		AdView adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);
		LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
		// Add the adView to it
		layout.addView(adView);
		// Initiate a generic request to load it with an ad
		adView.loadAd(new AdRequest());

		boutonScoreloopProfile = ((Button)findViewById(R.id.btn_edit_profile));
		boutonSubmitScore = ((Button)findViewById(R.id.btn_submit_score));
		
		try{
			ScoreloopManagerSingleton.init(this);
		}catch (Exception e) {
		}
		ScoreloopManagerSingleton.get().setOnScoreSubmitObserver(this);

		chronometre = (Chronometer)findViewById(R.id.chronometer1);
		chronometre.setOnChronometerTickListener(mOnChronometerTickListener);

		texteIntro = (TextView)findViewById(R.id.textView1);
		texteIntro.setText("0");

		texteScore = (TextView)findViewById(R.id.score);

		getPreference();

		imageBoutonBieber = (ImageButton)findViewById(R.id.imageButton1);
		imageBoutonBieber.setImageResource(R.drawable.bieber);

		// Bouton pour rejouer
		boutonRejouer = (Button)findViewById(R.id.replay);
		boutonRejouer.setVisibility(View.GONE);
		boutonRejouer.setOnClickListener(mResetListener);

		// Acquisition des boutons pour listeners
		((Button)findViewById(R.id.btn_submit_score)).setOnClickListener(this);
		((Button)findViewById(R.id.btn_edit_profile)).setOnClickListener(this);

		// Barre de progression pour ScoreLoop
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Submit on progress...");
		progressDialog.setCancelable(true);

		// Lecture MP3 du sample Audio
		try {
			MediaPlayer.create(this, R.raw.bieber).start();
		}
		catch (Exception e) {
		}
		
		// UPDATE FAN MEILLEUR JOUEUR 24H
		scoresController = new ScoresController(this);	
		scoresController.setSearchList(SearchList.getTwentyFourHourScoreSearchList());
		scoresController.setMode(null);
		scoresController.setRangeLength(1);
		scoresController.loadRangeAtRank(1);
		meilleurJoueur = (TextView)findViewById(R.id.bandeauMeilleurJoueur);
		imageFan = ((ImageView)findViewById(R.id.imagefan));
	}

	public void onDestroy() {
		super.onDestroy();
		ScoreloopManagerSingleton.destroy();
		tracker.stop();
	}

	/**
	 * Listener Chronometer
	 */
	OnChronometerTickListener mOnChronometerTickListener = new OnChronometerTickListener() {
		public synchronized void  onChronometerTick (Chronometer chronometer) {
			RebeccaBlackClic.this.i++;
			if (RebeccaBlackClic.this.i == 1){
				Toast.makeText(RebeccaBlackClic.this, "LET'S GO !!!!!", Toast.LENGTH_SHORT).show();
			}else
				if (RebeccaBlackClic.this.i == 10){
					Toast.makeText(RebeccaBlackClic.this, "COME ON !!!!!", Toast.LENGTH_SHORT).show();
				}else
					if (RebeccaBlackClic.this.i == 20){
						Toast.makeText(RebeccaBlackClic.this, "FASTER !!!!!", Toast.LENGTH_SHORT).show();
					}else
						if (RebeccaBlackClic.this.i == 30){
							Toast.makeText(RebeccaBlackClic.this, "CONTINUE ?!?!", Toast.LENGTH_SHORT).show();
						}else	
							if (RebeccaBlackClic.this.i == 40){
								Toast.makeText(RebeccaBlackClic.this, "20 SECONDS LEFT !!!!!", Toast.LENGTH_SHORT).show();
							}else
								if (RebeccaBlackClic.this.i == 62){
									Toast.makeText(RebeccaBlackClic.this, "REBECCAAAAAAAAAAAA !", Toast.LENGTH_SHORT).show();
									finish = true;
									SaveScore();
									boutonRejouer.setVisibility(0);
									MediaPlayer.create(RebeccaBlackClic.this, R.raw.bieber).start();
									chronometre.stop();
									boutonScoreloopProfile.setVisibility(1);
									boutonSubmitScore.setVisibility(1);
									chronometre.setBase(SystemClock.elapsedRealtime());
								}
		}
	};

	public void OnImageClick(View v) {
		if (!finish) {
			if (init == false){
				start();			  
			}
			texteIntro.setText((Integer.valueOf(texteIntro.getText().toString())+1)+"");
		}
	}

	public void SaveScore() {
		chronometre.stop();
		addPreference();
		tracker.trackEvent(
				"Clicks",  // Category
				"Save",  // Action
				"SaveScore", // Label
				0);       // Value
	}

	View.OnClickListener mResetListener = new OnClickListener() {
		public void onClick(View v) {
			chronometre.setBase(SystemClock.elapsedRealtime());
			chronometre.stop();
			texteIntro.setText("0");
			i=1;
			init = false;
			finish = false;
			boutonScoreloopProfile.setVisibility(View.GONE);
			boutonSubmitScore.setVisibility(View.GONE);
			tracker.trackEvent(
					"Game",  // Category
					"Clicks",  // Action
					"Replay", // Label
					0);       // Value
		}
	};

	public void start(){
		chronometre.setBase(SystemClock.elapsedRealtime());
		chronometre.start(); 
		if (boutonRejouer.getVisibility() == View.GONE ){
			boutonRejouer.setVisibility(1);
		}

		boutonScoreloopProfile.setVisibility(View.GONE);
		boutonSubmitScore.setVisibility(View.GONE);
		init = true ;
	}

	public void addPreference(){
		SharedPreferences settings = getSharedPreferences("user_score", Context.MODE_PRIVATE);
		if (settings.getString("score", "") == ""  || (Integer.valueOf(settings.getString("score", "")) < Integer.valueOf(String.valueOf(texteIntro.getText())))){
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("score", String.valueOf(texteIntro.getText()));
			texteScore.setText("Personal record " + String.valueOf(texteIntro.getText()));
			editor.commit();
		}
	}

	public void getPreference(){
		SharedPreferences settings = getSharedPreferences("user_score", Context.MODE_PRIVATE);
		if (settings.getString("score", "") == ""){
			texteScore.setText("No personal record");
			boutonSubmitScore.setVisibility(View.GONE);
		}else{
			texteScore.setText("Personal record " + settings.getString("score", ""));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()){
		case R.id.btn_submit_score:
			SharedPreferences settings = getSharedPreferences("user_score", Context.MODE_PRIVATE);
			if (!(settings.getString("score", "") == "")){
				progressDialog.show();
				ScoreloopManagerSingleton.get().onGamePlayEnded(Double.valueOf(settings.getString("score", "")),null);
				tracker.trackEvent(
						"Scoreloop",  // Category
						"Clicks",  // Action
						"SubmitScore", // Label
						0);       // Value
			}

			break;
		case R.id.btn_edit_profile:
			startActivity(new Intent(RebeccaBlackClic.this, EntryScreenActivity.class));
			tracker.trackEvent(
					"Scoreloop",  // Category
					"Clicks",  // Action
					"EditProfile", // Label
					0);       // Value
			break;
		}
	}

	@Override
	public void onScoreSubmit(int status, Exception error) {
		startActivity(new Intent(this, ShowResultOverlayActivity.class));
		progressDialog.cancel();
	}
	
	@Override
	public void requestControllerDidReceiveResponse(RequestController arg0) {
		final List<Score> scores = scoresController.getScores();
		Double score = ((Score)scores.get(0)).getResult();
		String url = ((Score)scores.get(0)).getUser().getImageUrl();
		String nom = ((Score)scores.get(0)).getUser().getDisplayName();
		if (nom != null && score != null){
			meilleurJoueur.setText("\nLAST 24H BEST FAN \n" + nom + "\n" + score.intValue() + " points");
			try {
				InputStream is = (InputStream) this.fetch(url);
				if (is != null){
					Drawable d = Drawable.createFromStream(is, "src");
					imageFan.setImageDrawable(d);
				}
			}catch (Exception e) { 
			}
		}else{
			meilleurJoueur.setText("\nNO LAST 24H BEST FAN : BE THE 1ST !!!\n");
		}


	}

	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	@Override
	public void requestControllerDidFail(RequestController arg0, Exception arg1) {
	}

}